import getPageTitle from '@/utils/page'
import router from '@/router'
import Nprogress from 'nprogress'
import { GET_TOKEN } from './utils/token'
import { useUserStoreHook } from './store/modules/user'
import { asyncRoute } from './router/routes'

router.beforeEach(async (to: any, from: any) => {
  Nprogress.start()
  const userStore = useUserStoreHook()
  // 在白名单中的判断情况
  document.title = getPageTitle(to.meta.title, to)

  //获取token,去判断用户登录、还是未登录
  const token = GET_TOKEN()

  if (!token || userStore.token !== token) {
    userStore.userLogout()
  } else {
    if (userStore.userInfo.id === 0) {
      await userStore.getUserInfo()
      await userStore.judgeHr()
      if (userStore.isHr === 1) {
        asyncRoute.forEach((item) => router.addRoute(item))
        return { ...to, replace: true }
      }
    }
  }
  return true
})
router.afterEach(() => {
  // 路由加载完成后关闭进度条
  document.getElementsByClassName('main-cont main-right')[0]?.scrollTo(0, 0)
  Nprogress.done()
})

router.onError(() => {
  // 路由发生错误后销毁进度条
  Nprogress.remove()
})
